﻿using System;

using System.Web;

namespace JCW.Common
{
    /// <summary>
    /// 缓存类
    /// </summary>
    public static class CacheHelper
    {
        /// <summary> 
        /// 插入Cache 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="o"></param> 
        /// <param name="key"></param> 
        public static void Insert<T>(T o, string key, int minutes)
        {
            HttpContext.Current.Cache.Insert(
                key,
                o,
                null,
                DateTime.Now.AddMinutes(minutes),
                System.Web.Caching.Cache.NoSlidingExpiration);
        }

        /// <summary> 
        /// 删除指定的Cache 
        /// </summary> 
        /// <param name="key">Cache的key</param> 
        public static void Remove(string key)
        {
            HttpContext.Current.Cache.Remove(key);
        }

        /// <summary> 
        /// 判断Cache是否存在 
        /// </summary> 
        /// <param name="key"></param> 
        /// <returns></returns> 
        public static bool Exists(string key)
        {
            return HttpContext.Current.Cache[key] != null;
        }

        /// <summary> 
        /// 取得Cache值，带类型 T 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="key"></param> 
        /// <param name="value"></param> 
        /// <returns></returns> 
        public static bool Get<T>(string key, out T value)
        {
            try
            {
                if (!Exists(key))
                {
                    value = default(T); // 
                    return false;
                }
                value = (T)HttpContext.Current.Cache[key];
            }
            catch
            {
                value = default(T);
                return false;
            }
            return true;
        }
    }
}